package cn.com.huak.www.sell.service.impl;

import cn.com.huak.www.sell.dto.OrderDTO;
import cn.com.huak.www.sell.enums.ResultEnum;
import cn.com.huak.www.sell.exception.OrderException;
import cn.com.huak.www.sell.service.BuyerService;
import cn.com.huak.www.sell.service.OrderMasterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author huak@wanggang
 * @date 2019/1/2 23:19
 */
@Service
@Slf4j
public class BuyerServiceImpl implements BuyerService {

    @Autowired
    private OrderMasterService orderMasterService;

    @Override
    public OrderDTO findOrderOne(String openid, String orderId) {
        return checkOrderOwner(openid, orderId);
    }

    @Override
    public OrderDTO cancel(String openid, String orderId) {
        OrderDTO one = checkOrderOwner(openid, orderId);
        if(null == one){
            log.error("【取消订单】当前的订单不存在....");
            throw new OrderException(ResultEnum.ORDER_NOT_EXIST);
        }
        return orderMasterService.cancel(one);
    }

    /**
     * 订单openid校验
     * @return
     */
    private OrderDTO checkOrderOwner(String openid, String orderId){
        OrderDTO one = orderMasterService.findOne(orderId);
        if(null == one){
            return null;
        }
        if(!one.getBuyerOpenid().equals(orderId)){
            log.error("【查询订单】查询订单的openid不相等....");
            throw new OrderException(ResultEnum.ORDER_OWNER_ERROR);
        }
        return one;
    }
}
